package Administrator;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;

import BookStore.managers.MinimumMarginMgr_Iface.MinimumMarginMgr;
import BookStore.managers.MinimumMarginMgr_Iface.MinimumMarginMgrHelper;
import Util.Util;

/**
 * This class represents the bookstore administrator
 * @author Loup
 *
 */
public class AdminMain {
	private static final String prop = "administrator.properties";
	private static String ip;
	private static String port;
	private static String BS;
	private static ORB orb;

	/**
	 * Aims to change the current minimum margin
	 * @param args
	 */
	public static void main(String[] args) {
		
		ip = Util.getPropertiesAttribute(prop, "ip");
		port = Util.getPropertiesAttribute(prop, "port");
		BS = Util.getPropertiesAttribute(prop, "BS");
		
		if(ip == null || port == null || BS == null){
			System.out.println("[ERROR] File "+prop +" is absent.");
			return;
		}
		
		
		
		try {
			MinimumMarginMgr mgr = getMarginMgr();
			//get the current margin
			float margin = mgr.getCurrentMargin();
			System.out
					.println("Your current minimum margin is " + margin + "%");
			System.out.println("Insert your new value :");
			BufferedReader keyboard = new BufferedReader(new InputStreamReader(
					System.in));
			String line = null;
			Float newMargin = null;
			while (newMargin == null) {
				line = keyboard.readLine();
				try {
					newMargin = Float.parseFloat(line);
				} catch (Exception e) {
					System.out.println("The inserted value is incorrect.");
				}

			}
			//update the margin
			mgr.setMargin(newMargin);
			System.out.println("The new margin is now "+ newMargin+"%");

		} catch (Exception e) {
			System.out.println("Sorry, the bookstore is unavailable...");
		}
		orb.destroy();

	}

	private static MinimumMarginMgr getMarginMgr() {

		Properties props = new Properties();
		props.put("org.omg.CORBA.ORBInitialHost", ip);
		props.put("org.omg.CORBA.ORBInitialPort", port);

		// initialize ORB
		orb = ORB.init(new String[] { "-ORBInitialPort", port,
				"-ORBInitiaHost", ip }, props);

		// retrieve Naming service
		org.omg.CORBA.Object objNameService = orb
				.string_to_object("corbaloc:iiop:" + ip + ":" + port
						+ "/NameService");
		NamingContext context = NamingContextHelper.narrow(objNameService);

		NameComponent[] name = new NameComponent[] { new NameComponent(
				"Margin", "Object" + BS) };
		try {
			return MinimumMarginMgrHelper.narrow(context.resolve(name));
		} catch (Exception e) {
			return null;
		}

	}
}
